package cn.wp.basic.service.impl;

import cn.wp.basic.constant.VerificationConstant;
import cn.wp.basic.exception.CustomException;
import cn.wp.basic.service.IVerificationCodeService;
import cn.wp.basic.util.SendMsgUtil;
import cn.wp.basic.util.StrUtils;
import cn.wp.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeServiceImpl extends BaseServiceImpl<User> implements IVerificationCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 门户网站 手机注册发的验证码
     * @param phone
     * @throws CustomException
     */
    @Override
    public void sendUserRegMobileCode(String phone) throws CustomException {
        this.sendMobileCode(phone+":"+ VerificationConstant.USER_REG, phone);
    }

    /**
     * 微信绑定手机号 发送的验证码
     * @param phone
     * @throws CustomException
     */
    @Override
    public void sendBinderMobileCode(String phone) throws CustomException {
        this.sendMobileCode(phone+":"+VerificationConstant.USER_BINDER, phone);
    }

    // 验证验证码
    public void sendMobileCode(String key,String phone) throws CustomException {
        // 1.获取随机数,放入redis
        String code = StrUtils.getComplexRandomString(4);

        // 获取redis中是否有验证码
        String codeValue = (String) redisTemplate.opsForValue().get(key);

        // 如果有
        if (!StringUtils.isEmpty(codeValue)){
            String beginTimer = codeValue.split(":")[1];
            if (System.currentTimeMillis()-Long.valueOf(beginTimer)<1000*60){
                // 2.验证码一分钟内不能获取多次
                throw new CustomException("验证码一分钟内不能获取多次!!!");
            }

            code = codeValue.split(":")[0];
            // 3.验证码获取在一分钟之后，五分钟之内，还是获取上一次的验证码
        }

        // 没有就直接是设置
        redisTemplate.opsForValue().set(key, code+":"+System.currentTimeMillis(), 5, TimeUnit.MINUTES);
        String content  = "验证码为：" + code + "请在五分钟内完成操作!";
        System.out.println(content);
        // SendMsgUtil.sendMsg(phone, content);
    }
}
